package net.searchdata.ref;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;

public class Entry23 {
	@Test
	public void test1PreRefactoring() {
		List<Integer> list = new ArrayList<Integer>();

		list.add(3);
		list.add(4);
		list.add(5);

		int result = 0;
		for (int i = 0; i < list.size(); i++) {
			result += ((Integer) list.get(i)).intValue();
		}
		assertThat(result, is(12));
	}

	@Test
	public void test1() {
		List<Integer> list = new ArrayList<Integer>();

		list.add(3);
		list.add(4);
		list.add(5);

		int result = 0;
		for (int i = 0; i < list.size(); i++) {
			result += ((Integer) list.get(i)).intValue();
		}
		assertThat(result, is(12));
	}

	@Test(expected = ClassCastException.class)
	public void test2() {
		List<String> strList = new ArrayList<String>();
		unsafeAdd(strList);
		System.out.println(strList.get(0));
	}

	private void unsafeAdd(List list) {
		list.add(123);
	}

	@Test
	public void test3() {
		Set<Integer> intSet1 = new HashSet<Integer>();
		Set<Integer> intSet2 = new HashSet<Integer>();

		intSet1.add(1);
		intSet1.add(2);
		intSet1.add(3);

		intSet2.add(2);
		intSet2.add(3);
		intSet2.add(4);

		assertThat(numElementsInCommon(intSet1, intSet2), is(2));
	}

	private int numElementsInCommon(Set<?> set1, Set<?> set2) {
		int result = 0;
		for (Object o : set1) {
			if (set2.contains(o)) {
				result++;
			}
		}

		return result;
	}
}